const request = require('request')
const baseCookie = require("./init.js");

function createWebAPIRequest(
	host,
	path,
	method,
	data,
	cookie,
	callback,
	errorcallback
) {
	if(cookie.match(/_csrf=[^(;|$)]+/g))
		data.csrf_token = cookie.match(/_csrf=[^(;|$)]+/g)[0].slice(6);
	else data.csrf_token = "";
	const proxy = cookie.split("__proxy__")[1];
	cookie = cookie.split("__proxy__")[0];
	const cryptoreq = Encrypt(data);
	const options = {
		url: `http://${host}${path}`,
		method: method,
		headers: {
			Accept: "*/*",
			"Accept-Language": "zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4",
			Connection: "keep-alive",
			"Content-Type": "application/x-www-form-urlencoded",
			Referer: "http://music.163.com",
			Host: "music.163.com",
			Cookie: baseCookie + (cookie ? "; " : "") + cookie,
			"User-Agent": randomUserAgent()
		},
		body: querystring.stringify({
			params: cryptoreq.params,
			encSecKey: cryptoreq.encSecKey
		}),
		proxy: proxy
	}
	console.log(`${host}`)
	request(options, function(error, res, body) {
		if(error) {
			errorcallback(error)
		} else {
			let cookie = res.headers["set-cookie"];
			if(Array.isArray(cookie)) {
				cookie = cookie
					.map(x => x.replace(/.music.163.com/g, ""))
					.sort((a, b) => a.length - b.length);
			}
			callback(body, cookie);
		}
	})
}

module.exports = {
	request,
	createWebAPIRequest
}